package com.example.common;

import com.example.util.LogUtils;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * @Classname HttpServerStart
 * @Description TODO
 * @Date 2023/4/24 15:08
 * @Created by XiongXiong
 * @Author: X.I.O
 *
 * http 启动
 */
public class HttpServerStart {

    private Integer port;

    private HttpServer httpServer;

    public HttpServerStart(Integer port) {
        try {
            this.port = port;
            httpServer = HttpServer.create(new InetSocketAddress(port), 1000);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public void start(){
        httpServer.setExecutor(null);
        httpServer.start();
        LogUtils.info("项目启动成功了，端口号为："+port);
    }

    public void addHttpHandler(String url, HttpHandlerModel commonHttpHandler){
        httpServer.createContext(url,commonHttpHandler);
    }

    public void addHttpContext(String path) throws Exception{
        HttpContext context = httpServer.createContext(path);
        HttpHandlerStaticContext httpHandlerStaticContext=new HttpHandlerStaticContext();
        context.setHandler(httpHandlerStaticContext::handleRequest);
    }
}